﻿using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Json;

namespace ProjectScheduling
{
    public static class Common
    {
        public static string Md5(string input)
        {
            byte[] hashBytes = MD5.HashData(Encoding.UTF8.GetBytes(input));
            return BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
        }
        public static T? ReadFile<T>(string path, bool safe = false)
            where T : class, new()
        {
            string p = $"{Application.StartupPath}\\data\\{path}.db";
            if (!File.Exists(p)) { return default; }
            using StreamReader sr = new(p);
            var str = sr.ReadToEnd();
            if (safe)
            {
                str = Encoding.UTF8.GetString(Convert.FromBase64String(str));
            }
            if (!string.IsNullOrEmpty(str))
            {
                return JsonSerializer.Deserialize<T>(str);
            }
            return default;
        }
        public static void WriteFile<T>(string path, T obj, bool safe = false) where T : class, new()
        {
            var dir = $"{Application.StartupPath}\\data\\";
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            string p = $"{dir}{path}.db";

            var str = JsonSerializer.Serialize(obj, new JsonSerializerOptions
            {
                WriteIndented = true,
                //AllowTrailingCommas = true,
                ReferenceHandler = ReferenceHandler.IgnoreCycles,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });
            if (safe)
            {
                str = Convert.ToBase64String(Encoding.UTF8.GetBytes(str));
            }
            using var sw = new StreamWriter(p);
            sw.Write(str);
            sw.Close();
        }
    }
}
